//
//  Playtime.swift
//  GhostWorld
//
//  Created by Kam on 2018/7/18.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation
import CoreData

private let entityName = CoreDataEntityName.playtime.rawValue
private let context = CoreDataHelper.getContext()

extension Playtime {
  static func get(audioID: Int) throws -> Playtime? {
    let request = NSFetchRequest<Playtime>()
    let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
    request.entity = entity
    request.predicate = NSPredicate(format: "userID = %@ && audioID = %@", "\(UserManager.shared.currentUser!.identifier)", "\(audioID)")
    do {
      let playtime = try context.fetch(request).first
      return playtime
    } catch let error {
      loggingPrint(error)
      throw error
    }
  }
  
  static func add(audioID: Int, seconds: Int) throws {
    do {
      if let currentPlaytime = try get(audioID: audioID) {
        currentPlaytime.seconds = currentPlaytime.seconds + Int16(seconds)
      } else {
        let newPlaytime = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! Playtime
        newPlaytime.id = NSUUID().uuidString
        newPlaytime.audioID = Int16(audioID)
        newPlaytime.userID = Int16(UserManager.shared.currentUser!.identifier)
        newPlaytime.seconds = Int16(seconds)
      }
      do {
        try context.save()
      } catch let error {
        loggingPrint(error)
        throw error
      }
    } catch let error {
      loggingPrint(error)
      throw error
    }
  }
  
  static func remove(_ playtime: Playtime) throws {
    context.delete(playtime)
    do {
      try context.save()
    } catch let error {
      loggingPrint(error)
      throw error
    }
  }
}
